package org.mat.ipaas.ucenter.service.modules.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.constant.SymbolConstant;
import org.mat.ipaas.ucenter.biz.common.util.SqlInjectionUtil;
import org.mat.ipaas.ucenter.biz.modules.system.mapper.SysDictMapper;
import org.mat.ipaas.ucenter.biz.modules.system.model.DuplicateCheckVo;
import org.mat.ipaas.ucenter.biz.modules.system.security.DictQueryBlackListHandler;
import org.mat.ipaas.ucenter.service.api.system.DuplicateCheckRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.model.DuplicateCheckVoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Title: DuplicateCheckAction
 * 重复校验工具
 * @Author 张代浩
 * @Date 2019-03-25
 * @Version V1.0
 */
@Slf4j
@RestController
@RequestMapping("/sys/duplicate")
@Api(tags = "重复校验")
public class DuplicateCheckController implements DuplicateCheckRestAPI {

    @Autowired
    SysDictMapper sysDictMapper;

    @Autowired
    DictQueryBlackListHandler dictQueryBlackListHandler;

    /**
     * 校验数据是否在系统中是否存在
     *
     * @return
     */
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    @ApiOperation("重复校验接口")
    public MatApiResponse<String> doDuplicateCheck(@SpringQueryMap DuplicateCheckVoDTO duplicateCheckVoDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        DuplicateCheckVo duplicateCheckVo = toDuplicateCheckVo(duplicateCheckVoDTO);

        Long num = null;

        log.debug("----duplicate check------：" + duplicateCheckVo.toString());


        //关联表字典（举例：sys_user,realname,id）
        //SQL注入校验（只限制非法串改数据库）
        final String[] sqlInjCheck = {duplicateCheckVo.getTableName(), duplicateCheckVo.getFieldName()};
        SqlInjectionUtil.filterContent(sqlInjCheck);
        // update-begin-author:taoyan date:20211227 for: JTC-25 【online报表】oracle 操作问题 录入弹框啥都不填直接保存 ①编码不是应该提示必填么？②报错也应该是具体文字提示，不是后台错误日志
        if (StringUtils.isEmpty(duplicateCheckVo.getFieldVal())) {
            MatApiResponse rs = new MatApiResponse();
            rs.setCode("500");
            rs.setSuccess(true);
            rs.setMessage("数据为空,不作处理！");
            return rs;
        }
        //update-begin-author:taoyan date:20220329 for: VUEN-223【安全漏洞】当前被攻击的接口
        String checkSql = duplicateCheckVo.getTableName() + SymbolConstant.COMMA + duplicateCheckVo.getFieldName() + SymbolConstant.COMMA;
        if (!dictQueryBlackListHandler.isPass(checkSql)) {
            return MatApiResponse.fail(dictQueryBlackListHandler.getError());
        }
        //update-end-author:taoyan date:20220329 for: VUEN-223【安全漏洞】当前被攻击的接口
        // update-end-author:taoyan date:20211227 for: JTC-25 【online报表】oracle 操作问题 录入弹框啥都不填直接保存 ①编码不是应该提示必填么？②报错也应该是具体文字提示，不是后台错误日志
        if (StringUtils.isNotBlank(duplicateCheckVo.getDataId())) {
            // [2].编辑页面校验
            num = sysDictMapper.duplicateCheckCountSql(duplicateCheckVo);
        } else {
            // [1].添加页面校验
            num = sysDictMapper.duplicateCheckCountSqlNoDataId(duplicateCheckVo);
        }

        if (num == null || num == 0) {
            // 该值可用
            return MatApiResponse.success("该值可用！");
        } else {
            // 该值不可用
            log.info("该值不可用，系统中已存在！");
            return MatApiResponse.fail("该值不可用，系统中已存在！");
        }
    }

    private DuplicateCheckVo toDuplicateCheckVo(DuplicateCheckVoDTO duplicateCheckVoDTO) {
        if (duplicateCheckVoDTO == null) {
            return null;
        }
        DuplicateCheckVo duplicateCheckVo = new DuplicateCheckVo();
        duplicateCheckVo.setTableName(duplicateCheckVoDTO.getTableName());
        duplicateCheckVo.setFieldName(duplicateCheckVoDTO.getFieldName());
        duplicateCheckVo.setFieldVal(duplicateCheckVoDTO.getFieldVal());
        duplicateCheckVo.setDataId(duplicateCheckVoDTO.getDataId());
        return duplicateCheckVo;
    }

    /**
     * VUEN-2584【issue】平台sql注入漏洞几个问题
     * 部分特殊函数 可以将查询结果混夹在错误信息中，导致数据库的信息暴露
     *
     * @param e
     * @return
     */
    @ExceptionHandler(java.sql.SQLException.class)
    public MatApiResponse<?> handleSQLException(Exception e) {
        String msg = e.getMessage();
        String extractvalue = "extractvalue";
        String updatexml = "updatexml";
        if (msg != null && (msg.toLowerCase().indexOf(extractvalue) >= 0 || msg.toLowerCase().indexOf(updatexml) >= 0)) {
            return MatApiResponse.fail("校验失败，sql解析异常！");
        }
        return MatApiResponse.fail("校验失败，sql解析异常！" + msg);
    }
}
